# -*- coding: utf8 -*-


import time
import json
import pymongo
import config
import datetime

from scrapy import Spider
from scrapy.http import Request
from sqlhelper import SqlHelper


class ExchangePairs(Spider):
    name = 'pairs'

    def __init__(self, name = None, **kwargs):
        super(ExchangePairs, self).__init__(name, **kwargs)

        # 连接mongodb
        client = pymongo.MongoClient('47.254.26.182', 27017)
        # client = pymongo.MongoClient('localhost', 27017)
        self.db = client.bt_news

    def start_requests(self):
        url = 'https://data.block.cc/api/v1/market_pairs'

        yield Request(
            url = url,
            dont_filter=True,
            headers = {
                'Host': 'data.block.cc',
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
            },
            meta = {

            },
            callback = self.exchange_info
        )

    def exchange_info(self, response):
        # 获取json中的数据，对应交易所信息
        body = json.loads(response.body)

        data = body.get('data')

        for exchange in data:
            # 交易所名称
            name = exchange.get('name')

            if name == 'okcoincom':
                # 交易对名称
                symbol_pairs = exchange.get('symbol_pairs')

                if symbol_pairs:
                    for pair in symbol_pairs:
                        pair_name = pair

                        # 入库
                        data_pairs = {
                            'exchange_name': 'okcoin',
                            'pair_name': pair_name,
                            'addtime': time.localtime()
                        }

                        # 存到mongo
                        # self.db.bt_transaction_pair.insert(data_pairs)

# 数据库结构
'''

'''